import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";

import http from '../../http/index'
import { useDispatch } from "react-redux";
import { ConversationType, MessageType } from "../../domain/im/entity";

const initialState: { value: any } = {
  value: {
    list: [],
    current: 0, // 当前选中的
  },
};

try {
  const list = localStorage.getItem("conversation_list");
  const current = localStorage.getItem("conversation_current");
  if (list) {
    initialState.value.list = JSON.parse(list);
    initialState.value.current = current ? parseInt(current) : 0
  }
} catch (error) {
  console.error('Error initializing conversation state:', error);
}


export const fetchConversationList: any = createAsyncThunk('conversation/list', async (lastTargetId?) => {
  const list = localStorage.getItem("conversation_list");
  const response = await http.get('/conversation/list');
  const serverList = response.data; // 服务器返回的会话列表
  const localList = list ? JSON.parse(list) : []; // 本地会话列表
  const newList = [...localList]; // 合并后的会话列表

  for (var item of serverList) {
    const index = newList.findIndex((item1: any) => item1.targetId == item.targetId);
    if (index == -1) {
      newList.push(item);
    } else {
      newList[index] = {
        ...item,
        userName: item.userName,
        portrait: item.portrait ?? '',
        unreadCount: item.unreadCount,
        remark: item.remark
      };
    }
  }


  const tops = newList.filter((item: any) => item.top == true);


  const notTops = newList.filter((item: any) => item.top == false).slice().sort((a: any, b: any) => {
    const timeA = new Date(a.timestamp).getTime();
    const timeB = new Date(b.timestamp).getTime();
    return timeB - timeA;
  });


  const sortedData = [...tops, ...notTops]


  return { sortedData, lastTargetId };
})


export const refreshConversationByTargetId: any = createAsyncThunk('conversation/refreshSingle', async (item: any) => {
  const { targetId, type } = item;
  if (type == ConversationType.private) {
    const response = await http.get(`/refreshSingleConversationByUserId?targetId=${targetId}`);
    const { userPortrait, nickName, remark } = response.data;
    return { userPortrait, userName: remark ? remark : nickName, targetId };
  } else if (type == ConversationType.group) {
    const response = await http.get(`/refreshSingleConversationByGroupId?targetId=${targetId}`);
    const { userPortrait, userName } = response.data;
    return { userPortrait, userName, targetId };
  }
  return {};
})




export const conversationSlice = createSlice({
  name: "conversation",
  initialState,
  reducers: {
    deleteConversation: (state, action) => {
      const { targetId, currentTargetId } = action.payload;
      const list = state.value.list;
      const index = list.findIndex((item: any) => item.targetId == targetId);
      const newList = [...list.slice(0, index), ...list.slice(index + 1)];
      state.value.list = newList;
      localStorage.setItem("conversation_list", JSON.stringify(newList));

      if (targetId == currentTargetId) {
        state.value.current = 0;
        localStorage.setItem("conversation_current", "0");
      }

    },

    clearUnreadCount: (state, action) => {
      const str: any = localStorage.getItem("conversation_list");
      if (str) {
        const list = JSON.parse(str);
        const { targetId } = action.payload;
        const index = list.findIndex((item: any) => item.targetId == targetId);
        if (index != -1) {
          list[index].unreadCount = 0;
          localStorage.setItem('conversation_list', JSON.stringify(list));
          state.value.list = list;
        }
      }
    },

    updateLastMessageaddNum: (state, action) => {
      const str: any = localStorage.getItem("conversation_list");
      if (str) {
        const list = JSON.parse(str);
        const { lastMessage, timestamp, targetId } = action.payload;
        const index = list.findIndex((item: any) => item.targetId == targetId);
        if (index != -1) {
          list[index].lastMessage = lastMessage;
          list[index].timestamp = timestamp;
          list[index].unreadCount = parseInt((list[index].unreadCount ?? 0)) + 1;
          localStorage.setItem('conversation_list', JSON.stringify(list));
          state.value.list = list;
        }
      }
    },

    updateLastMessage: (state, action) => {
      const str: any = localStorage.getItem("conversation_list");
      if (str) {
        const list = JSON.parse(str);
        const { lastMessage, timestamp, targetId } = action.payload;
        const index = list.findIndex((item: any) => item.targetId == targetId);
        if (index != -1) {
          list[index].lastMessage = lastMessage;
          list[index].timestamp = timestamp;
          localStorage.setItem('conversation_list', JSON.stringify(list));
          state.value.list = list;
        }
      }
    },
    addConversation: (state, action) => {
      const conversation = action.payload;
      const str: any = localStorage.getItem("conversation_list");
      let list = str ? JSON.parse(str) : [];
      const index = list.findIndex((item: any) => item.targetId == conversation.targetId);
      if (index != -1) {
        list.splice(index, 1);
      }
      const newList = [action.payload, ...list];
      state.value = {
        list: newList,
        current: 0,
      };
      localStorage.setItem('conversation_current', `0`);
      localStorage.setItem('conversation_list', JSON.stringify(newList));

    },
    changeIndex: (state, action) => {
      state.value.current = action.payload;
      localStorage.setItem('conversation_current', `${action.payload}`)
    }
  },

  extraReducers: (builder) => {
    builder.addCase(fetchConversationList.fulfilled, (state, action) => {
      const { sortedData, lastTargetId } = action.payload;
      const user = localStorage.getItem("user");
      if (user) {
        localStorage.setItem('conversation_list', JSON.stringify(sortedData))
        state.value.list = sortedData;
        if (lastTargetId) {
          const index = sortedData.findIndex((item: any) => item.targetId == lastTargetId);
          state.value.current = index > 0 ? index : 0;
        } 
        // else {
        //   console.log("走这个了")
        //   state.value.current = 0;
        // }
      }
    }).addCase(refreshConversationByTargetId.fulfilled, (state, action) => {
      const { userPortrait, userName, targetId } = action.payload;
      const list = state.value.list;
      if (list.length > 0) {
        const index = list.findIndex((item: any) => item.targetId == targetId);

        console.log("---------")
        console.log(list[index]);
        list[index].userPortrait = userPortrait;
        list[index].userName = userName;
        localStorage.setItem('conversation_list', JSON.stringify(list));
      }
    })
  },
})

export const { deleteConversation, clearUnreadCount, updateLastMessage, changeIndex, addConversation, updateLastMessageaddNum } = conversationSlice.actions;

export default conversationSlice.reducer